<?php

namespace iBrand\Shop\Backend\Http\Controllers;

use Encore\Admin\Facades\Admin as LaravelAdmin;
use Encore\Admin\Layout\Content;
use iBrand\Component\Goods\Models\Goods;
use iBrand\Component\Goods\Models\GoodsProduct;
use iBrand\Component\Purchase\Models\StockRecord;
use iBrand\Component\Purchase\Models\Transfer;
use iBrand\Component\Goods\Models\Supplier;
use iBrand\Component\Purchase\Repositories\TransferItemRepository;
use iBrand\Component\Goods\Repositories\GoodsProductRepository;
use iBrand\Component\Purchase\Repositories\TransferRepository;
use iBrand\Shop\Backend\Repository\O2oGoodsProductsRepository;
use iBrand\Shop\Backend\Repository\O2oGoodsRepository;
use iBrand\Component\Purchase\Repositories\StockRecordRepository;
use iBrand\Shop\Backend\Model\Shop;
use iBrand\Shop\Backend\Service\CommonService;
use iBrand\Shop\Core\Models\ClerkAdminRelation;
use iBrand\Shop\Core\Models\O2oGoodsProducts;
use iBrand\Shop\Core\Service\WarehouseService;
use Illuminate\Http\Request;
use Validator;
use DB;

class TransferController extends Controller
{
    protected $commonService;
    protected $transferRepository;
    protected $transferItemRepository;
    protected $goodsProductRepository;
    protected $o2oGoodsProductsRepository;
    protected $o2oGoodsRepository;
    protected $stockRecordRepository;
    protected $warehouseService;

    public function __construct(CommonService $commonService,
                                TransferRepository $transferRepository,
                                TransferItemRepository $transferItemRepository,
                                GoodsProductRepository $goodsProductRepository,
                                O2oGoodsProductsRepository $o2oGoodsProductsRepository,
                                O2oGoodsRepository $o2oGoodsRepository,
                                StockRecordRepository $stockRecordRepository,
                                WarehouseService $warehouseService)
    {
        $this->commonService = $commonService;
        $this->transferRepository = $transferRepository;
        $this->transferItemRepository = $transferItemRepository;
        $this->goodsProductRepository = $goodsProductRepository;
        $this->o2oGoodsProductsRepository = $o2oGoodsProductsRepository;
        $this->o2oGoodsRepository = $o2oGoodsRepository;
        $this->stockRecordRepository = $stockRecordRepository;
        $this->warehouseService = $warehouseService;
    }

    public function index()
    {
        $condition = $this->searchCondition();

        $list = $this->transferRepository->getTransferPaginate(session('shop_id'), $condition[0], $condition[1]);

        return LaravelAdmin::content(function (Content $content) use ($list) {

            $content->header('调拨单');

            $content->breadcrumb(
                ['text' => '采购管理', 'url' => 'warehouse/transfer', 'no-pjax' => 1],
                ['text' => '调拨单', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '调拨单']
            );

            $content->body(view('shop-backend::transfer.index', compact('list')));
        });
    }

    private function searchCondition()
    {
        $where = [];
        $time = [];

        if (request('code')) {
            $where['code'] = ['like', '%' . request('code') . '%'];
        }

        if (!empty(request('etime')) && !empty(request('stime'))) {
            $where['created_at'] = ['<=', request('etime')];
            $time['created_at'] = ['>=', request('stime')];
        }

        if (!empty(request('etime'))) {
            $time['created_at'] = ['<=', request('etime')];
        }

        if (!empty(request('stime'))) {
            $time['created_at'] = ['>=', request('stime')];
        }

        return [$where, $time];
    }

    public function show()
    {
        $order_no = request('order_no');
        $transfer = $this->transferRepository->findWhere(['code' => $order_no])->first();

        return LaravelAdmin::content(function (Content $content) use ($transfer) {

            $content->header('查看调拨详情');

            $content->breadcrumb(
                ['text' => '采购管理', 'url' => 'warehouse/transfer', 'no-pjax' => 1],
                ['text' => '调拨单', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '调拨单']
            );

            $content->body(view('shop-backend::transfer.show', compact('transfer')));
        });
    }

    public function create()
    {
        $suppliers = Supplier::where('status', 1)->get(['id', 'name', 'code'])->toArray();
        $shops = Shop::where('is_enable', 1)->get();
        $specList = $this->commonService->getSpecList();
        $colors = $specList['colors'];
        $sizes = $specList['sizes'];
        $order_type = 'transfer';
        $button_text = '调拨';

        return LaravelAdmin::content(function (Content $content) use ($suppliers, $colors, $sizes, $order_type, $button_text, $shops) {

            $content->header('库存调拨单');

            $content->breadcrumb(
                ['text' => '采购管理', 'url' => 'warehouse/transfer', 'no-pjax' => 1],
                ['text' => '调拨单', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '调拨单']
            );

            $content->body(view('shop-backend::purchase.create', compact('suppliers', 'sizes', 'colors', 'order_type', 'button_text', 'shops')));
        });
    }

    public function store(Request $request)
    {
        $order = $request->input('order');
        $order = json_decode($order, true);
        $goods = $request->input('goods');
        $goods = json_decode($goods, true);
        if (empty($goods) || empty($order)) {
            return $this->ajaxJson(false, [], 500, '请选择商品');
        }

        if (!$order['outShopId'] || !$order['inShopId'] || $order['outShopId'] == $order['inShopId']) {
            return $this->ajaxJson(false, [], 500, '调拨门店错误');
        }

        $goodsValidator = $this->validateGoods($goods);
        if ($goodsValidator->fails()) {

            return $this->ajaxJson(false, [], 500, $goodsValidator->messages()->first());
        }

        $goodsCollect = collect($goods);
        try {
            DB::beginTransaction();
            $clerk = ClerkAdminRelation::where('admin_id', auth('admin')->user()->id)->first();

            $transferData = [
                'out_shop_id' => $order['outShopId'],
                'in_shop_id' => $order['inShopId'],
                'code' => 'AL' . date('YmdHis') . mt_rand(10000000, 99999999),
                'clerk_id' => $clerk ? $clerk->clerk_id : 0,
                'total' => $goodsCollect->sum('quantity'),
                'remark' => $order['remark'],
            ];

            $transfer = $this->transferRepository->create($transferData);

            $total_amount = 0;
            foreach ($goods as $good) {
                $factory_price = isset($good['price']) ? $good['price'] : 0;
                if ($good['currentSku']) {
                    $product = $this->goodsProductRepository->getProductBySku($good['currentSku']);
                    $item_id = $product->id;
                    $item_type = GoodsProduct::class;

                    if (!$factory_price) {
                        $factory_price = $product->goods->factory_price;
                        $good['price'] = $factory_price;
                    }
                } else {
                    $item_id = $good['goods_id'];
                    $item_type = Goods::class;
                }

                if (!$factory_price) {
                    return $this->ajaxJson(false, [], 500, '进货价不存在');
                }

                $total_amount += $good['price'] * $good['quantity'];

                $this->warehouseService->addTransferItem($transfer->id, $good, $item_id, $item_type);

                $this->warehouseService->addTransferStockRecord($transfer, $good, $item_id, $item_type);


                if ($transfer->in_shop_id) {
                    $inO2oGoods = $this->o2oGoodsRepository->findWhere(['status' => 1, 'goods_id' => $good['goods_id'], 'shop_id' => $transfer->in_shop_id])->first();
                    if (!$inO2oGoods) {
                        $inO2oGoods = $this->o2oGoodsRepository->create([
                            'goods_id' => $good['goods_id'],
                            'shop_id' => $transfer->in_shop_id,
                            'price' => $factory_price,
                        ]);
                    }
                    $this->warehouseService->addO2oGoodsProduct($transfer->in_shop_id, $inO2oGoods->id, $good['goods_id'], $good['quantity'], 'Transfer', Transfer::TYPE_IN, $item_id);
                    $inO2oGoods->restoreStock($good['quantity']);
                }

                if ($transfer->out_shop_id) {
                    $outO2oGoods = $this->o2oGoodsRepository->findWhere(['status' => 1, 'goods_id' => $good['goods_id'], 'shop_id' => $transfer->out_shop_id])->first();
                    $outO2oGoodsId = $outO2oGoods->id;
                    $this->deleteOutO2oGoodsProduct($outO2oGoodsId, $good, $item_id, $transfer->out_shop_id);

                    $outO2oGoods->reduceStock($good['quantity']);
                }

            }

            $transfer->total_amount = $total_amount;
            $transfer->save();

            DB::commit();

            return $this->ajaxJson();
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getTraceAsString());

            return $this->ajaxJson(false, '', 500, $exception->getMessage());
        }
    }

    /**
     * @param $goods
     *
     * @return \Illuminate\Validation\Validator
     */
    public function validateGoods($goods)
    {
        $rules = [
            '*.goods_name' => 'required',
            '*.goods_no' => 'required',
            '*.goods_id' => 'required',
            '*.currentSku' => 'required',
            '*.color' => 'required',
            '*.color_id' => 'required',
            '*.size' => 'required',
            '*.size_id' => 'required',
            '*.beforeNumber' => 'required|integer|min:0',
            '*.quantity' => 'required|integer|min:0',
        ];

        $message = [
            "required" => ":attribute 不能为空",
            "integer" => ":attribute 必须是整数",
            "min" => ":attribute 必须大于等于0",
        ];

        $attributes = [
            '*.goods_name' => '商品名称',
            '*.goods_no' => '商品货号',
            '*.goods_id' => '商品id',
            '*.beforeNumber' => '调拨前数量',
            '*.quantity' => '调拨数量',
        ];

        $validator = Validator::make($goods, $rules, $message, $attributes);

        return $validator;
    }


    public function deleteOutO2oGoodsProduct($o2oGoodsId, $good, $product_id, $out_shop_id)
    {
        $o2oGoodsProduct = $this->o2oGoodsProductsRepository->findWhere(['shop_id' => $out_shop_id, 'o2o_goods_id' => $o2oGoodsId, 'goods_id' => $good['goods_id'], 'product_id' => $product_id])->first();
        $o2oGoodsProduct->store_nums = $o2oGoodsProduct->store_nums - $good['quantity'];
        $o2oGoodsProduct->save();
    }
}